class AdjustSalaryService
  include StatusObject
  include Serviceable

  def initialize(staff, params)
    @staff ||= staff
    @params ||= params
  end

  def call
    @staff.transaction do
      @log = @staff.adjust_logs.create!(@params)
      @staff.reset_salary(@params[:basic]) if current_month?
      handle_salary
    end
    Status.new(success: true)
  rescue => e
    Rails.logger.debug e.message
    Status.new(success: false, message: e.message)
  end

  private
  def salary
    @salary = @staff.salaries.by_created_month(@params[:started_at]).last
  end

  def handle_salary
    if salary.present?
      @salary.update!(basic: @params[:basic]) unless @salary.status.present?
    else
      @staff.initialize_salary(@params[:started_at], @params[:basic])
    end
  end

  def current_month?
    Time.now.last_month.strftime("%Y%m") == @params[:started_at]
  end
end
